#!/usr/bin/env python3
# -*- coding: utf-8 -*-
"""
PyInstaller hook for ddddocr
解决ddddocr打包时的模型文件和依赖问题
"""

from PyInstaller.utils.hooks import collect_data_files, collect_submodules
import os
import sys

# 收集ddddocr的所有数据文件
datas = collect_data_files('ddddocr')

# 收集ddddocr的所有子模块
hiddenimports = collect_submodules('ddddocr')

# 添加onnxruntime相关的隐藏导入
hiddenimports.extend([
    'onnxruntime',
    'onnxruntime.capi',
    'onnxruntime.capi.onnxruntime_pybind11_state',
    'onnxruntime.capi._pybind_state',
    'numpy',
    'numpy.core',
    'numpy.core._multiarray_umath',
])

# 强制手动添加ddddocr的关键模型文件
try:
    import ddddocr
    ddddocr_path = os.path.dirname(ddddocr.__file__)

    # 关键模型文件列表
    critical_models = ['common.onnx', 'common_det.onnx', 'common_old.onnx']

    for model_file in critical_models:
        model_path = os.path.join(ddddocr_path, model_file)
        if os.path.exists(model_path):
            # 确保模型文件被正确添加到根目录
            datas.append((model_path, 'ddddocr'))
            print(f"✅ 强制添加关键模型文件: {model_file}")
        else:
            print(f"⚠️ 关键模型文件不存在: {model_file}")

    # 查找所有其他模型文件
    for root, dirs, files in os.walk(ddddocr_path):
        for file in files:
            if file.endswith(('.onnx', '.pb', '.model', '.bin', '.dat', '.json')):
                full_path = os.path.join(root, file)
                rel_path = os.path.relpath(full_path, ddddocr_path)
                target_dir = os.path.join('ddddocr', os.path.dirname(rel_path)) if os.path.dirname(rel_path) else 'ddddocr'

                # 避免重复添加
                if not any(data[0] == full_path for data in datas):
                    datas.append((full_path, target_dir))
                    print(f"📁 添加ddddocr文件: {file} -> {target_dir}")

except ImportError:
    print("❌ 警告: 无法导入ddddocr，跳过手动模型文件收集")
except Exception as e:
    print(f"❌ 收集ddddocr模型文件时出错: {e}")

# 添加额外的运行时依赖
hiddenimports.extend([
    'ddddocr.ddddocr',
    'ddddocr.utils',
])

print(f"🎯 ddddocr hook: 收集到 {len(datas)} 个数据文件")
print(f"🎯 ddddocr hook: 收集到 {len(hiddenimports)} 个隐藏导入")

# 打印所有收集到的数据文件用于调试
for src, dst in datas:
    if 'ddddocr' in src:
        print(f"   📄 {os.path.basename(src)} -> {dst}")
